package bTree.LeetCode;

import java.util.List;

public class K个一组翻转链表 {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k==1){
            return head;
        }
        ListNode dummy=new ListNode(0,head);
        int cnt=1;
        ListNode leftNode =head,rightNode=head;
        ListNode preNode=dummy;
        while (rightNode!=null){
            if(cnt==k){
                ListNode proNode=rightNode.next;
                reverseNode(leftNode,rightNode);
                preNode.next=rightNode;
                preNode=leftNode;
                cnt=1;
                leftNode=rightNode=proNode;
            }else {
                cnt++;
                rightNode=rightNode.next;
            }

        }
        return dummy.next;

    }

    private void reverseNode(ListNode leftNode, ListNode rightNode) {
        ListNode left=leftNode,right=leftNode.next,proNode=rightNode.next;
        while (true){
            right.next=left;
            if(right==rightNode){
                break;
            }
            left=right;
            right=proNode;
            proNode=right.next;
        }
    }
}